//
//  IMMessageViewController.m
//  markmap
//
//  Created by 甘世清 on 2024/5/19.
//

#import "IMMessageViewController.h"
#import "IMMessageModel.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import <QKeyboardEmotionView/QKeyboardEmotionView-umbrella.h>
#import "IMMessageManager.h"
#import "BaseIMTableViewCell.h"
#import "IMtextMessageTableViewCell.h"
#import "IMImageMessageTableViewCell.h"
#import "IMPeopleViewController.h"
#import "IMJinDouMessageTableViewCell.h"
@interface IMMessageViewController ()<QInputBarViewDelegate,QInputBarViewDataSource,InputBoardDataSource,InputBoardDelegate,QExtendBoardViewDelegate,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic , strong) QInputBarView * putView;
@property (nonatomic , strong) QKeyboardManager * keyBoardManager;
@end

@implementation IMMessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.zx_navTitle = self.model.name;
    self.view.backgroundColor = SQColor(@"#363636");
    WS(weakSelf);
    [self zx_setRightBtnWithImg:SQGetImage(@"shanchu") clickedBlock:^(ZXNavItemBtn * _Nonnull btn) {
        IMPeopleViewController * vc = [[IMPeopleViewController alloc]init];
        vc.model = weakSelf.model;
        [weakSelf.navigationController pushViewController:vc animated:YES];
        [vc setClenrBlock:^{
            [weakSelf.jsonArray removeAllObjects];
            [weakSelf.tableView reloadData];
        }];
    }];
}
- (void)SQ_UIViewForSelfView{
    self.zx_navLineView.hidden = NO;
    self.zx_navBarBackgroundColor = SQColor(@"#363636");
    self.zx_navLineViewBackgroundColor = SQColor(@"#696969");
    self.showEmpty = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.zx_navBar.mas_bottom);
        make.bottom.equalTo(self.view.mas_bottom).offset(-FootHeight);
    }];
    [self SQ_tableViewAddRefresh];
    [self SQ_Header];
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(scrollViewWillBeginDragging:)];
    [self.tableView addGestureRecognizer:tap];
    [self.keyBoardManager addBottomInputBarView:self.putView belowViewController:NO];
    [self.keyBoardManager bindTextView:self.putView.inputTextView];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(SQ_DataForArray:) name:@"IMMessageModel" object:nil];
    
}
- (void)SQ_Header{
    WS(weakSelf);
    NSArray * array = [SQFMDBManager SQ_UserAcquireID:weakSelf.model.roomId size:weakSelf.model.noReadCount page:weakSelf.jsonArray.count];
    if (array.count > 0) {
        [weakSelf.jsonArray insertObjects:array atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [array count])]];
        IMMessageModel * model = array.lastObject;
        [weakSelf insertAndScrollToBottom:model needClearInputText:YES];
    }else{
        [weakSelf.tableView reloadData];
    }
    //设置全部已读
    [[IMMessageManager sharedIMManager]SQ_readAll:weakSelf.model];
    [weakSelf.tableView.mj_header endRefreshing];
}
- (void)SQ_Foother{
    [self.tableView.mj_footer endRefreshing];
}

//来消息了
-(void)SQ_DataForArray:(NSNotification*)notification{
  WS(weakSelf);
    IMMessageModel * model =[IMMessageModel mj_objectWithKeyValues:notification.object];
  if ([self.model.roomId isEqualToString:model.roomId]) {
      if ([self.jsonArray containsObject:model]) {
          return;
      }
      [weakSelf.jsonArray addObject:model];
      [weakSelf insertAndScrollToBottom:model needClearInputText:NO];
      [[IMMessageManager sharedIMManager]SQ_readAll:weakSelf.model];
  }
    DTLog(@"输出完了");
}

//点击了系统键盘的发送按钮
- (void)inputBarView:(QInputBarView *)inputBarView onKeyboardSendClick:(NSString *)inputNormalText {
    if (![inputNormalText isNotEmpty]) {return;}
    [self.putView clearInputTextBySend];
    //发消息
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:inputNormalText forKey:@"content"];
    [dic setObject:@"200" forKey:@"order"];
    [dic setObject:@"0" forKey:@"msgType"];
    [dic setObject:self.model.roomId forKey:@"roomId"];
    NSMutableDictionary * ext = [[NSMutableDictionary alloc]init];
    [ext setObject:[UserModel share].name forKey:@"name"];
    [ext setObject:[UserModel share].portrait forKey:@"portrait"];
    [ext setObject:[UserModel share].userid forKey:@"peopleId"];
    [dic setObject:[ext mj_JSONString] forKey:@"ext"];
    [[SQWebSocket shareManager]SQ_send:[dic mj_JSONString] isSend:^(BOOL isSend) {
        if (isSend) { //发送成功就刷新ui
        } else {//发送失败就提示
            inputBarView.inputTextView.text = inputNormalText;
            [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"发送失败,请检查网络!")];
        }
    }];
}




#pragma  mark UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.jsonArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WS(weakSelf);
  IMMessageModel * model = [[IMMessageManager sharedIMManager]SQ_SetUPModel:indexPath array:weakSelf.jsonArray];
  [self.tableView registerClass:NSClassFromString(model.cellIndentify) forCellReuseIdentifier:model.cellIndentify];
    BaseIMTableViewCell * cell = [IMMessageManager SQ_getCell:model table:tableView indexPath:indexPath];
    //图片点击回调
    [cell setImageBlock:^(UIImageView * _Nonnull image) {
        [weakSelf.keyBoardManager hideAllBoardView];
        [[IMMessageManager sharedIMManager] SQ_celldidSelecttable:tableView indexPath:indexPath array:weakSelf.jsonArray];
    }];
   
    return cell;
}

//cell点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.keyBoardManager hideAllBoardView];
   
}


 
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    IMMessageModel * model = [self.jsonArray objectAtIndex:indexPath.item];
    return [IMMessageManager SQ_getCellHeight:model];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [[NSNotificationCenter defaultCenter] postNotificationName:SJChangePopMenuIfNeeded object:nil];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [[NSNotificationCenter defaultCenter] postNotificationName:SJShowPopMenuIfNeeded object:nil];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (!decelerate) {
        [[NSNotificationCenter defaultCenter] postNotificationName:SJShowPopMenuIfNeeded object:nil];
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    //用户手动拖动tableview，隐藏所有面板和键盘
    [self.keyBoardManager hideAllBoardView];
}
 

//添加到array中 + reload和滚到底部。 needClearInputText: 是否需要清空文本框输入的内容
- (void)insertAndScrollToBottom:(IMMessageModel *)contentModel needClearInputText:(BOOL)needClearInputText {
    if (contentModel ==nil) {
        return;
    }
    //添加到array中
    NSTimeInterval animationDuration = needClearInputText ? [self.putView clearInputTextBySend] : 0;
    //reloadData并滚到底部
    [self reloadDataAndScrollToBottomAnimated:YES animationDelay:animationDuration];
}
//reloadData并滚到底部
- (void)reloadDataAndScrollToBottomAnimated:(BOOL)animated animationDelay:(NSTimeInterval)animationDelay {
     BOOL resultAnimated = animated;
    if (animationDelay == 0){
        //如果textView的文本只有一行，那么清空输入框的时候，不会走onWholeInputViewHeightDidChange回调，也不会重新设置tableView的contentInset。所以就无需延时reloadData
        [self.tableView reloadData];
        [self scrollToBottomAnimated:resultAnimated];
    } else {
    //textView的文本大于一行，那么清空输入框的时候，会重设tableView的contentInset（并且我还是在0.2秒的动画里重设的），如果这时候reloadData，在低性能设备上会出现tableView来回上下移动的问题
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(animationDelay * NSEC_PER_SEC)), dispatch_get_main_queue(),  ^{
            [self.tableView reloadData];
            [self scrollToBottomAnimated:resultAnimated];
        });
    }
}
//滚到底部
-(void)scrollToBottomAnimated:(BOOL)animated {
    NSInteger rows = [self.tableView numberOfRowsInSection:0];
    if (rows > 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:rows - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:animated];
    }
}
#pragma mark - InputBoardDelegate
//整个“输入View”的高度发生变化（整个View包含bar和表情栏或者键盘，但是不包含底部安全区高度）
- (void)keyboardManager:(QKeyboardManager *)keyboardManager onWholeInputViewHeightDidChange:(CGFloat)wholeInputViewHeight reason:(WholeInputViewHeightDidChangeReason)reason {
    WS(weakSelf);
    BOOL alreadyAtBottom = [self SQ_alreadyAtBottom:weakSelf.tableView];
    UIEdgeInsets insets = UIEdgeInsetsZero;
    insets.top = 0;
    insets.bottom = wholeInputViewHeight;// - UIInputBarViewMinHeight;
    //对应聊天界面，随着底部输入框的frame.y的变化，为了保持tableview一直都在输入条的上方，修改tableview的contentInset
    self.tableView.contentInset = insets;
    self.tableView.scrollIndicatorInsets = insets;
    if (reason == WholeInputViewHeightDidChangeReasonWillAddToSuperView){ //聊天界面，tableView要滚到底部
        dispatch_async(dispatch_get_main_queue(), ^{
        [self scrollToBottomAnimated:NO];
     });
        return;
    }
    if (reason == WholeInputViewHeightDidChangeReasonTextDidSend) {
        //是点击“发送”按钮清空输入框里的多行文字导致的输入栏高度变化
        return;
    }
    if (alreadyAtBottom) {
        //用自己的animations，问题就是会闪屏，尤其是tableview滚在上方时候 闪的越狠；好处是tableview在切换时候很跟手
        [UIView animateWithDuration:keyboardManager.inputBarHeightChangeAnimationDuration delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            [self scrollToBottomAnimated:NO];
        } completion:nil];
    } else {
        [self scrollToBottomAnimated:YES];
    }
}

#pragma mark - QInputBarViewDataSource
//@return 输入条上的UITextView，返回你自定义的UITextView
- (UITextView *)textViewForInputBarView:(QInputBarView *)inputBarView {
    FSTextView *tv = [[FSTextView alloc] init];
    tv.layer.cornerRadius = 4;
    [tv setShowsVerticalScrollIndicator:NO];
    [tv setShowsHorizontalScrollIndicator:NO];
    tv.returnKeyType = UIReturnKeySend;
    tv.textColor = UIColor.whiteColor;
    tv.font = FONT_MEDIUM(16);
    return tv;
}
#pragma mark - QInputBarViewDelegate
// 输入框的高度发生了改变（因为输入框里的文字行数变化了），注意这里仅仅是TextView输入框的高度发生了变化的回调；becauseSendText：YES表示是因为调用了clearInputTextBySend去发送文本
- (void)inputBarView:(QInputBarView *)inputBarView inputTextView:(UITextView *)inputTextView heightDidChange:(CGFloat)changeValue becauseSendText:(BOOL)becauseSendText {
    //这里要告知Manager类
    [self.keyBoardManager inputTextViewHeightDidChange:becauseSendText];
}
-(BOOL)SQ_alreadyAtBottom:(UITableView*)view{
    if (((NSInteger)view.contentOffset.y) == ((NSInteger)view.contentSize.height + view.adjustedContentInset.bottom - CGRectGetHeight(view.bounds))) {
        return YES;
    }
    return NO;
}


//@return 点加号按钮弹出的拓展面板View的高度
- (CGFloat)keyboardManagerExtendBoardHeight:(QKeyboardManager *)keyboardManager {
    return 140+FootHeight;
}

//@return 点加号按钮弹出的拓展面板View，且无需设置frame
- (UIView *)keyboardManagerExtendBoardView:(QKeyboardManager *)keyboardManager{
    QExtendBoardView *boardView = [[QExtendBoardView alloc] init];
    boardView.delegate = self;
    boardView.backgroundColor = SQColor(@"#2c2c2c");
    QExtendBoardItemModel *photoItem = [[QExtendBoardItemModel alloc]initWithNormalIconImage:SQGetImage(@"xiangce") title:@"相册"];
    QExtendBoardItemModel *photoItem2 = [[QExtendBoardItemModel alloc]initWithNormalIconImage:SQGetImage(@"xiangji") title:@"相机"];
    QExtendBoardItemModel *photoItem3 = [[QExtendBoardItemModel alloc]initWithNormalIconImage:SQGetImage(@"fasongdingwei") title:@"定位"];
    boardView.extendBoardItems = @[photoItem,photoItem2,photoItem3];
    return boardView;
}
#pragma mark - QExtendBoardViewDelegate
//点击拓展面板的cell
- (void)didSelectExtendBoardItem:(QExtendBoardItemModel *)shareMenuItem atIndex:(NSInteger)index {
    [[IMMessageManager sharedIMManager] SQ_sendMsg:self.model type:index];
}

/// 点击+按钮
/// - Parameters:
///   - inputBarView: inputBarView description
///   - extendSwitchButton: extendSwitchButton description
- (void)inputBarView:(QInputBarView *)inputBarView onExtendButtonClick:(UIButton *)extendSwitchButton {
    [_keyBoardManager switchToExtendBoardKeyboard];
}


- (void)dealloc{
    DTLog(@"当前im类是否释放");
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.keyBoardManager.viewControllerWillDisappear = NO;
    [[IQKeyboardManager sharedManager] setEnable:NO];
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 避免手势返回的时候输入框往下掉
    self.keyBoardManager.viewControllerWillDisappear = YES;
    [[IQKeyboardManager sharedManager] setEnable:YES];
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;;
}

- (QInputBarView *)putView{
    if (!_putView) {
        _putView = [[QInputBarView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, UIInputBarViewMinHeight)];
        _putView.delegate = self;
        _putView.dataSource = self;
        QInputBarViewConfiguration *config = [QInputBarViewConfiguration defaultInputBarViewConfiguration];
        config.inputBarBackgroundColor = SQColor(@"#2c2c2c");
        config.inputBarBoardColor = UIColor.clearColor;
        config.textViewBackgroundColor = SQColor(@"#363636");
        config.textColor = UIColor.whiteColor;
        config.voiceButtonHidden = YES;
        config.emotionButtonHidden = YES;
        [_putView setupWithConfiguration:config];
    }
    return _putView;
}
- (QKeyboardManager *)keyBoardManager{
    if (!_keyBoardManager) {
        _keyBoardManager = [[QKeyboardManager alloc]initWithViewController:self];
        _keyBoardManager.dataSource = self;
        _keyBoardManager.delegate = self;
    }
    return _keyBoardManager;
}

@end
